<?php

namespace App\Models;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * 项目
 * App\Models\Project
 */
class Project extends Model
{
    use SoftDeletes;

    protected $guarded = ['id'];

    /**
     * @param DateTimeInterface $date
     * @return string
     * @author: lxk
     * @date: 2025-08-23 11:09
     */
    protected function serializeDate(DateTimeInterface $date) : string
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * 关联关系 1:N 查询项目下的部门
     * @return HasMany
     */
    function departments(): HasMany
    {
        return $this->hasMany(Department::class)
            ->select(['id', 'title', 'company_id', 'project_id', 'part_company_id', 'department_id', 'parent_type'])
            ->where('project_id', '>', 0)->where('part_company_id', 0);
    }

    /**
     * 关联关系 1:N 项目对应的分类目录模板
     * @return BelongsTo
     */
    function classifyTemplate(): BelongsTo
    {
        return $this->belongsTo(ClassifyTemplate::class, 'template_id', 'id', 'template')->select(['id', 'title']);
    }

    /**
     * 关联关系 1:N 项目对应的分类目录模板
     * @return BelongsTo
     */
    function combination(): BelongsTo
    {
        return $this->belongsTo(DossierCombination::class, 'combination_id', 'id')->select(['id', 'title']);
    }

    /**
     * 关联关系 N:N 查询项目下的user
     * @return BelongsToMany
     */
    function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'project_user')->withPivot('creator_id'); //获取中间表字段
    }


    /**
     * 关联关系 1:N 项目下的的参建单位
     * @return HasMany
     */
    function partCompanies(): HasMany
    {
        return $this->hasMany(PartCompany::class)
            ->select(['id', 'type', 'company_id', 'project_id', 'title', 'contract_num', 'status', 'creator_id'])
            ->orderBy('type');
    }

    /**
     * 关联关系 1:N 项目所属公司
     * @return BelongsTo
     */
    function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }

    /**
     * 关联关系 1:N 检索配置在项目下的分类目录
     * @return HasMany
     */
    function projectClassifies(): HasMany
    {
        return $this->hasMany(ProjectClassify::class);
    }


}
